# -*- coding: utf-8 -*-
from datetime import datetime

from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from app import db, login_manager

class User(UserMixin, db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    email = db.Column(db.String(125))
    avatar = db.Column(db.String(255))
    avatar_large = db.Column(db.String(255))
    avatar_small = db.Column(db.String(255))
    gender = db.Column(db.Boolean, default=None)      # (0, male) (1, female)
    website = db.Column(db.String(255))
    location = db.Column(db.String(255))
    signature = db.Column(db.String(125))
    brief = db.Column(db.String(500))
    password_hash = db.Column(db.String(128))
    last_login = db.Column(db.DateTime, default=datetime.now())
    active = db.Column(db.Integer)      # (0, normal) (1, not jihuo) (2, forbiden)

    def __init__(self, name, email, password, avatar=None,
                avatar_small=None, avatar_large=None, gender=None,
                website=None, location=None, signature=None, brief=None):
        self.name = name
        self.email = email
        self.password_hash = self.set_password(password)
        self.avatar = avatar
        self.avatar_small = avatar_small
        self.avatar_large = avatar_large
        self.gender = gender
        self.website = website
        self.location = location
        self.signature = signature
        self.brief = brief

    def get_password(self, password):
        raise Exception('Password is read only')

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def get_id(self):
        return str(self.id)

    def __str__(self):
        return self.name


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

